package org.cy.algorithm.chapter_02;

import java.util.Arrays;

import static org.cy.algorithm.util.AlgorithmUtil.copyArray;
import static org.cy.algorithm.util.AlgorithmUtil.createRandomArray;

public class InsertionSort {

    private void sortArray(int[] arr) {
        if (arr == null || arr.length <= 1) {
            return;
        }

        for (int i = 1; i < arr.length; i++) {
            int key = arr[i];
            int j = i - 1;
            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];
                j--;
            }
            arr[j + 1] = key;
        }
    }

    public static void main(String[] args) {
        for (int i = 1; i <= 10000; i++) {
            int[] randomArray = createRandomArray(100);
            int[] mergeSortArray = copyArray(randomArray);
            new InsertionSort().sortArray(mergeSortArray);
            int[] systemSortArray = copyArray(mergeSortArray);
            Arrays.sort(systemSortArray);
            if (!Arrays.equals(systemSortArray, mergeSortArray)) {
                System.out.printf("Oops!\n");
                return;
            }
        }
        System.out.printf("OK");
    }


}
